package cn.donting.jme.editor.scene.wrapper;

import cn.donting.jme.editor.scene.Wrapper;
import com.jme3.export.*;
import com.jme3.light.Light;
import com.jme3.math.ColorRGBA;
import org.checkerframework.checker.units.qual.C;

import java.io.IOException;

public class LightWrapper extends Wrapper<Light> {

    private float intensity = 1;
    private ColorRGBA color = new ColorRGBA();

    public LightWrapper() {

    }

    @Override
    public void initValue(Light light) {
        super.initValue(light);
        this.color = light.getColor().clone();
        intensity = 1;
    }

    public void setColor(ColorRGBA color) {
        this.color = color.clone();
    }

    public ColorRGBA getColor() {
        checkColor();
        return color;
    }

    public void setIntensity(float intensity) {
        this.intensity = intensity;
    }

    public float getIntensity() {
        checkColor();
        return intensity;
    }

    public ColorRGBA toColorRGBA() {
        return color.mult(intensity);
    }

    /**
     * 限定 color为255 之内
     */
    private void checkColor() {
        float mult = 1;
        if (color.a < 0 || color.a > 1) {
            mult = Math.max(color.a, mult);
        }
        if (color.r < 0 || color.r > 1) {
            mult = Math.max(color.r, mult);
        }
        if (color.g < 0 || color.g > 1) {
            mult = Math.max(color.g, mult);
        }
        if (color.b < 0 || color.b > 1) {
            mult = Math.max(color.b, mult);
        }
        if (mult != 1) {
            color = new ColorRGBA(color.toVector4f().divide(mult));
            intensity = mult;
        }
    }

    @Override
    public void write(JmeExporter ex) throws IOException {
        super.write(ex);
        OutputCapsule capsule = ex.getCapsule(this);
        capsule.write(color, "color", null);
        capsule.write(intensity, "intensity", 1);
    }

    @Override
    public void read(JmeImporter im) throws IOException {
        super.read(im);
        InputCapsule capsule = im.getCapsule(this);
        color = (ColorRGBA) capsule.readSavable("color", null);
        intensity = capsule.readFloat("intensity", 1);
    }
}
